/**
 * 指针目标获取接口测试用例
 *
 * Created by snowingsea on 2020/03/07.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));
const randomstring = require('randomstring');

const common = require('./../../../common');
const Administrator = require('./../../../../models/administrator');
const uri = require('./../../uri');
const benchmark = require('./../../../../benchmark/analyse-files/logic_bombs');

module.exports = describe('/GET functions/:id/malloc/:name.json', function () {
  const administrator = new Administrator();
  const newUserIds = [];
  let projectVersion = {};
  let func = {};
  function url(functionId, variableName) {
    return `/functions/${functionId}/malloc/${variableName}.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then((res) => {
        projectVersion = res;
        return projectVersion.getAllFunctions(benchmark);
      })
      .then(([item]) => {
        func = item;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'get');
  common.should.be.tester(uri, url, 'get');

  // 正常获取
  [
    { variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }), typeName: 'int' },
    { variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }), elementTypeName: 'char', length: 10 },
  ].forEach((variable, index) => {
    it(`it should ${index === 0 ? 'GET' : 'get'} malloc variable with ${JSON.stringify(variable)}`, function (done) {
      func.addMallocVariable(variable.variableName, variable)
        .then(() => projectVersion.project.creator.login())
        .then(() => {
          chai.request(uri)
            .get(url(func.functionId, variable.variableName))
            .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
            .end((err, res) => {
              res.should.have.status(200);
              common.should.be.functionMallocVariableMessage(res.body);
              res.body.functionId.should.be.eql(func.functionId);
              res.body.variableName.should.be.eql(variable.variableName);
              if (variable.typeName) {
                res.body.typeName.should.be.eql(variable.typeName);
              } else {
                res.body.elementTypeName.should.be.eql(variable.elementTypeName);
                res.body.length.should.be.eql(variable.length);
              }
              done();
            });
        })
        .catch(done);
    });
  });

  // 不可获取不存在的函数的指针目标
  it('it should fail to get malloc variable when the function is not exists', function (done) {
    new Promise((resolve) => {
      chai.request(uri)
        .get(url('000000000000000000000000', randomstring.generate({ length: 16, charset: 'alphabetic' })))
        .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
        .end((err, res) => {
          res.should.have.status(404);
          common.should.be.errorMessage(res.body);
          resolve();
        });
    })
      .then(done)
      .catch(done);
  });

  // 不可获取他人项目的函数指针目标
  it('it should fail to get malloc variable when the project is not yours', function (done) {
    let newUser;
    const variableName = randomstring.generate({ length: 16, charset: 'alphabetic' });
    administrator.createRandomTester()
      .then((tester) => {
        newUser = tester;
        newUserIds.push(tester.userId);
        return tester.getToken();
      })
      .then(() => {
        chai.request(uri)
          .get(url(func.functionId, variableName))
          .set('Authorization', `Bearer ${newUser.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可获取不存在的指针目标
  it('it should fail to get malloc variable when the variable is not exists', function (done) {
    chai.request(uri)
      .get(url(func.functionId, randomstring.generate({ length: 16, charset: 'alphabetic' })))
      .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
      .end((err, res) => {
        res.should.have.status(404);
        common.should.be.errorMessage(res.body);
        done();
      });
  });
});
